<template>
  <div class="xtx-pagination" v-if="total>0">
    <a href="javascript:;" v-if="myCurrentPage>1" @click="changePager(myCurrentPage-1)">上一页</a>
    <a href="javascript:;" v-else class="disabled">上一页</a>
    <span v-if="pager.start>1">...</span>
    <a href="javascript:;" :class="{active:i===myCurrentPage}" v-for="i in pager.btnArr" :key="i" @click="changePager(i)">{{i}}</a>
    <span v-if="pager.end<pager.pageCount">...</span>
    <a href="javascript:;" v-if="myCurrentPage<pager.pageCount" @click="changePager(myCurrentPage+1)">下一页</a>
    <a href="javascript:;" v-else class="disabled">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    total: { // 总评论条数
      type: Number,
      default: 100
    },
    pageSize: { // 每页评论条数
      type: Number,
      default: 10
    },
    currentPage: { // 当前页码
      type: Number,
      default: 1
    }
  },
  setup (props, { emit }) {
    const count = 5 // 按钮个数
    const myCurrentPage = ref(1) // 当前页码
    const myTotal = ref(100) // 总评论条数
    const myPageSize = ref(10) // 每页评论条数

    const pager = computed(() => {
    // 总页数=总评论条数/每页评论条数 向上取整
      const pageCount = Math.ceil(myTotal.value / myPageSize.value)
      const offset = Math.floor(count / 2) // 首尾偏移量
      let start = myCurrentPage.value - offset // 首按钮码
      let end = start + count - 1 // 尾按钮码
      if (start < 1) {
        start = 1
        end = start + count - 1 > pageCount ? pageCount : (start + count - 1) // 这么写以免在页数过少时出现bug
      }
      if (end > pageCount) {
        end = pageCount
        start = end - count + 1 < 1 ? 1 : (end - count + 1)
      }
      const btnArr = [] // 显示按钮码
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return { pageCount, btnArr, start, end }
    })
    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })
    // 切换分页
    function changePager (page) {
      myCurrentPage.value = page
      emit('current-change', page)
    }

    return { myCurrentPage, pager, changePager }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
